package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;


    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.检查参数
        dto.checkParam();
        //赛选条件
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        if (null != dto.getChannelId()){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (null !=dto.getStatus()){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        if(StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        wrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        page(page,wrapper);
        //结果返回
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }


    //发布文章
    @Override
    @GlobalTransactional
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //判断参数状态
        if (dto == null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //文章的保存
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //dto数据里面的就图片的部分不一样。需要单独的处理然后添加进wmNews里面
        if(dto.getImages() != null && dto.getImages().size() > 0){
            //从集合转换为字符串
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagesStr);
        }
        //如果选择自动，值为-1，存储报错，暂时修改为null,后面补
        if(dto.getType().equals(-1)){
            wmNews.setType(null);
        }

        //补充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short)1);
        wmNews.setSubmitedTime(new Date());

        //文章已经拿到了,我们需要去判断文章是新增的还是修改的
        saveOrUpdateWmNews(wmNews);
        //如果文章是草稿就不需要保存素材和文章之间的关系 ,就直接把文章上传保存的文章表里面即可,素材内容还可能进行改变
        if (dto.getStatus().equals(WmNews.Status.NORMAL)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //首先,内容中的图片的与素材的关联关系,从内容中抽取图片的数据
        List<String> contentImagesUrl =excuyte(dto);
        //保存素材与内容图片的关系
        short type = 0;
        saveRelativeInfoForContent(wmNews,contentImagesUrl,type);

        //保存素材与封面图片的关系
        saveRelativeInfoForCover(wmNews,dto, contentImagesUrl);

        //文章发布完毕,等待审核环节
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 保存素材与封面图片的关系
     * @param contImageurls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(WmNews wmNews, WmNewsDto dto, List<String> contImageurls) {
        List<String> images = dto.getImages();
        //封面的图片是--单图,多图就不用管了,就查找素材和图的id 保存在他们的关系表里面

        //自动的,需要去获取内容里面的图片,更新文章状态
        if (dto.getType() == -1){
            if (contImageurls.size()>3){
                images = contImageurls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType((short)3);
            }else if (contImageurls.size()>=1){
                images = contImageurls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType((short)1);
            }else {
                wmNews.setType((short)0);
            }
        }
        //更新wmNWE数据
        updateById(wmNews);

        //保存素材与封面图片的关系
        saveRelativeInfoForContent(wmNews,images,(short) 1);


    }

    private void saveRelativeInfoForContent(WmNews wmNews, List<String> imageUrls, short type) {
        //1.判断文章内容里面的图片是否有内容,有则保存关系
        if (imageUrls.size()>0 ){
            //图片有可能重复,去重
            imageUrls = imageUrls.stream().distinct().collect(Collectors.toList());
            //根据url去查询素材对象
            Integer id = WmThreadLocalUtil.getUser().getId();
            LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(WmMaterial::getUrl,imageUrls);
            wrapper.eq(WmMaterial::getUserId,id);
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper);

            List<Integer> wmMaterialIds = wmMaterials.stream().map(material -> (material.getId())).collect(Collectors.toList());

            //判断素材数据在使用的过程中是否被删除了
            if (null == wmMaterials || wmMaterials.size() != imageUrls.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            wmNewsMaterialMapper.saveRelations(wmMaterialIds,wmNews.getId(), (short) 0);
        }



    }

    /**
     * 抽取文章中的图片地址
     * @param dto
     * @return
     */
    private List<String> excuyte(WmNewsDto dto) {
        String content = dto.getContent();
        List<String> list = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                list.add((String) map.get("value"));
            }
        }

        return list;
    }

    /**
     * 保存或更新文章数据
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (null != wmNews.getId()){
            //更新---删除原有的数据,包括文章与素材的关系
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialMapper.delete(wrapper);
            updateById(wmNews);
        }else{
            //新增
            save(wmNews);
        }
    }
}
